package com.control.back.halo.bookmark.service.impl;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.control.back.halo.basic.dao.IBaseDao;
import com.control.back.halo.basic.service.impl.BaseServiceImpl;
import com.control.back.halo.bookmark.dao.IBlogDao;
import com.control.back.halo.bookmark.entity.Article;
import com.control.back.halo.bookmark.parse.Url2io;
import com.control.back.halo.bookmark.service.IBlogService;
import com.hankcs.hanlp.HanLP;

@Service("blogService")
public class BlogServiceImpl extends BaseServiceImpl<Article, Long> implements IBlogService {

    // private static Logger logger = Logger.getLogger(BlogServiceImpl.class);

    @Resource(name = "blogDaoImpl")
    private IBlogDao blogDao;

    @Override
    public IBaseDao<Article, Long> getBaseDao() {
        return this.blogDao;
    }

    @Override
    public Article getArticle(String url) {
        Article article = blogDao.getByUrlHashCode(url.hashCode());
        if (article == null || StringUtils.isBlank(article.getTitle())) {
            if (article == null) {
                article = new Article();
            }
            String jsonStr;
            try {
                jsonStr = Url2io.getArticleByUrl(url);
                JSONObject articleJson = JSONObject.parseObject(jsonStr);
                /**
                 * String url ; String date; String content; String title;
                 */
                
                String content = articleJson.getString("content");
                
                article.setContent(content);
                article.setUrl(articleJson.getString("url"));
                article.setUrlHashCode(articleJson.getString("url").hashCode());
                article.setTitle(articleJson.getString("title"));
                article.setPublishDate(articleJson.getDate("date"));
                
                Document document = Jsoup.parse(content);
                String textContent = document.text();
                article.setTextContent(textContent);
                List<String> sentenceList = HanLP.extractSummary(textContent, 10);
                article.setDigest(sentenceList.toString());
                
                blogDao.save(article);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return article;
    }
}
